10-3 r磢慷MBNB捋PX

strcmp 指令用於比較字串內容的異同,例如:

Example 1: 10-字元與字串/string301.mstr1 = 'today'; str2 = 'tomorrow'; str3 = 'today'; out1 = strcmp(str1, str2) % 比較兩字串 str1 和 str2 out2 = strcmp(str1, str3) % 比較兩字串 str1 和 str3 out1 = 0 out2 = 1

由上例得知,out1 的值是 0,表示 str1 和 str2 內容不相等;out2 的值是 1,表示 str1 和 str3 內容相等。

Hint
在C 語言中,strcmp 指令也用來作字串比較,但在兩字串相等時,回傳值是 0,這和 MATLAB 的 strcmp 指令剛好相反。請特別小心!

strncmp 指令用於比較字串的前 n 個字元,例如:

Example 2: 10-字元與字串/string302.mstr1 = 'today'; str2 = 'tomorrow'; strncmp(str1, str2, 2) % 比較 str1 及 str2 兩字串的前 2 個字元 ans = 1

strcmp 及 strncmp 指令亦可用於字串異質陣列,例如:

Example 3: 10-字元與字串/string303.mA = {'台北', '台中', '高雄'}; % 建立字串異質陣列 A B = {'台北', '台南', '花蓮'}; % 建立字串異質陣列 B out1 = strcmp(A, B) % 比較字串異質陣列 A 與 B 的每個元素是否相同 out2 = strncmp(A, B, 1) % 比較字串異質陣列 A 與 B 的每個元素的的第一個字元是否相同 out1 = 1 0 0 out2 = 1 1 0

findstr 指令可以尋找在某一個長字串中的子字串(Substrings),並傳回其起始位置,例如:

Example 4: 10-字元與字串/string304.mstring = '我最喜歡的運動是網球'; pattern = '網球'; position = findstr(string, pattern) position = 9

strrep 指令用於字串尋找及代換,例如:

Example 5: 10-字元與字串/string305.mstring = '我最喜歡的運動是網球'; pattern = '網球'; pattern2 = '蝦球'; newString = strrep(string, pattern, pattern2) newString = 我最喜歡的運動是蝦球

strtok 指令可根據一給定的分界字元(Delimiting Characters),將一字串拆解成數個字串,預設的分界字元為空白字元,例如:

Example 6: 10-字元與字串/string306.minput_string = 'ee cs econ stat me'; remainder = input_string; parsed = ''; % 建立一空字元陣列 while (any(remainder)) [chopped, remainder] = strtok(remainder); parsed = strvcat(parsed, chopped); end parsed parsed = ee cs econ stat me

在上例中,strvcat 指令的作用是將拆解下來的字串內容(即儲存在字串變數 chopped 中) 加到二維字元陣列 parsed 中。

一般而言,若是在 MATLAB 指令視窗或是程式碼直接指定含有大五碼的字串,MATLAB 7.x 會直接使用 unicode 來儲存內碼。但是如果直接從檔案讀取文字,則 MATLAB 會對每一個中文文字拆成兩個 byte 來讀入,造成「凸槌」。舉例來說,在本章範例程式目錄內,有一檔案為「big5.txt」,其內容為「我是Roger」,我們可用下列程式將此檔案內容讀至一個字串變數:

Example 7: 10-字元與字串/string307.mfid = fopen('big5.txt'); line = fgetl(fid) % 讀取一列檔案內容並印出 fclose(fid); leng=length(line) % 顯示字串變數長度 line = 我是Roger leng = 7

(有關讀取此文字檔之方法,可詳見本書第十八章「檔案輸出及輸入」。)在上述範例中,我們將字串變數 line 印出,發覺前面兩個中文字已經變成亂碼,而且line 的長度是 9,而不是 7 ,欲詳查原因,我們可用 double 指令將之轉成 ASCII 碼,就能一目了然:

Example 8: 10-字元與字串/string308.mfid = fopen('big5.txt'); line = fgetl(fid); % 讀取一列檔案內容 fclose(fid); double(line) % 顯示字串內碼 ans = Columns 1 through 5 25105 26159 82 111 103 Columns 6 through 7 101 114

原來 MATLAB 在讀入中文字串時,將每一個中文字的 2-byte 分開來讀,造成原先的兩個中文字變成四個字串元素。(若使用 MATLAB 6.x,雖然外觀看不出來,但內部儲存方式仍是將一個中文字看成兩個單原來儲存。)欲解決此問題,在 MATLAB 7.x 可用 native2unicode 指令,來將中文的 2-byte 「結合」在一起,例如:

Example 9: 10-字元與字串/string309.mfid = fopen('big5.txt'); line = fgetl(fid); % 讀取一列檔案內容 fclose(fid); line2 = native2unicode(line, 'big5') % 使用 native2unicode 將被拆開的中文字結合在一起 leng = length(line2) % 顯示字串長度 line2 = 我是Roger leng = 7

因此,如果您的程式需要常常讀取中文檔案(或是其它 double bytes 的文字),native2unicode指令將是你的最佳伙伴!

若要在 MATLAB 5.3 或 6.x 執行上述範例,請將 native2unicode(line, 'big5') 改成 xlate(line) ,即可得到同樣的結果。

「xlate」指令是筆者向美國總公司查詢如何解決上述問題所得到的解答,在 MATLAB 5.3 版後才有支援,但在 MATLAB 7.x 已經功成身退。此指令是 「undocumented」,因此在 MATLAB 線上支援或紙本手冊都未提到。


MATLAB程式設計:入門篇